/**
 * 课程购买页面
 * /packageTeacher/pages/courses/purchase/index
 */

const Router = require('../../../utils/router')
const Storage = require('../../../utils/storage')
const Logger = require('../../../utils/logger')
const Track = require('../../../utils/track')
const Auth = require('../../../utils/auth')

Page({
  data: {
    title: '确认购买',
    loading: true,
    courseId: '',
    course: null,
    
    // 订单信息
    order: {
      totalAmount: 0,
      discountAmount: 0,
      finalAmount: 0
    },
    
    // 支付相关
    paymentMethods: [
      { id: 'wechat', name: '微信支付', icon: '💳', selected: true },
      { id: 'balance', name: '余额支付', icon: '💰', selected: false, balance: 0 }
    ],
    selectedPayment: 'wechat',
    
    // 优惠券
    coupons: [],
    selectedCoupon: null,
    showCoupons: false,
    
    // 购买状态
    purchasing: false
  },

  onLoad(options) {
    const { courseId } = options
    this.setData({ courseId })
    
    Logger.info('Page loaded: /packageTeacher/pages/courses/purchase/index', { courseId })
    Track.trackPageView('/packageTeacher/pages/courses/purchase/index', { courseId })
    
    this.loadPurchaseInfo()
  },

  /**
   * 加载购买信息
   */
  async loadPurchaseInfo() {
    try {
      this.setData({ loading: true })
      
      // 并发加载课程信息、优惠券、用户余额
      const [course, coupons, userBalance] = await Promise.all([
        this.getCourseInfo(this.data.courseId),
        this.getUserCoupons(this.data.courseId),
        this.getUserBalance()
      ])
      
      // 更新支付方式中的余额显示
      const paymentMethods = this.data.paymentMethods
      const balanceMethod = paymentMethods.find(m => m.id === 'balance')
      if (balanceMethod) {
        balanceMethod.balance = userBalance
      }
      
      this.setData({
        course,
        coupons,
        paymentMethods
      })
      
      this.calculateOrderAmount()
      
    } catch (error) {
      Logger.error('Failed to load purchase info', error)
      wx.showToast({
        title: error.message || '加载失败',
        icon: 'none'
      })
    } finally {
      this.setData({ loading: false })
    }
  },

  /**
   * 获取课程信息
   */
  async getCourseInfo(courseId) {
    // 模拟API
    await new Promise(resolve => setTimeout(resolve, 500))
    
    return {
      id: courseId,
      title: '零基础爵士舞入门',
      cover: '/images/course1.jpg',
      price: 199,
      originalPrice: 299,
      teacher: {
        name: '李老师',
        avatar: '/images/teacher1.jpg'
      }
    }
  },

  /**
   * 获取用户优惠券
   */
  async getUserCoupons(courseId) {
    // 模拟API
    await new Promise(resolve => setTimeout(resolve, 300))
    
    return [
      {
        id: 1,
        name: '新用户优惠券',
        description: '满100减20',
        discountAmount: 20,
        minAmount: 100,
        expireDate: '2025-12-31',
        applicable: true
      },
      {
        id: 2,
        name: '舞蹈课程专享',
        description: '满200减50',
        discountAmount: 50,
        minAmount: 200,
        expireDate: '2025-12-31',
        applicable: true
      },
      {
        id: 3,
        name: '限时优惠券',
        description: '满300减30',
        discountAmount: 30,
        minAmount: 300,
        expireDate: '2025-12-31',
        applicable: false
      }
    ]
  },

  /**
   * 获取用户余额
   */
  async getUserBalance() {
    // 模拟API
    await new Promise(resolve => setTimeout(resolve, 200))
    return 156.8
  },

  /**
   * 计算订单金额
   */
  calculateOrderAmount() {
    const { course, selectedCoupon } = this.data
    let totalAmount = course.price
    let discountAmount = 0
    
    // 应用优惠券
    if (selectedCoupon && selectedCoupon.applicable && totalAmount >= selectedCoupon.minAmount) {
      discountAmount = selectedCoupon.discountAmount
    }
    
    const finalAmount = Math.max(0, totalAmount - discountAmount)
    
    this.setData({
      'order.totalAmount': totalAmount,
      'order.discountAmount': discountAmount,
      'order.finalAmount': finalAmount
    })
  },

  /**
   * 选择支付方式
   */
  onPaymentSelect(e) {
    const { method } = e.currentTarget.dataset
    
    // 更新支付方式选中状态
    const paymentMethods = this.data.paymentMethods.map(m => ({
      ...m,
      selected: m.id === method
    }))
    
    this.setData({
      paymentMethods,
      selectedPayment: method
    })
  },

  /**
   * 显示优惠券列表
   */
  onShowCoupons() {
    this.setData({ showCoupons: true })
  },

  /**
   * 隐藏优惠券列表
   */
  onHideCoupons() {
    this.setData({ showCoupons: false })
  },

  /**
   * 选择优惠券
   */
  onCouponSelect(e) {
    const { coupon } = e.currentTarget.dataset
    
    if (!coupon.applicable) {
      wx.showToast({
        title: '优惠券不适用',
        icon: 'none'
      })
      return
    }
    
    if (this.data.course.price < coupon.minAmount) {
      wx.showToast({
        title: `满${coupon.minAmount}元可用`,
        icon: 'none'
      })
      return
    }
    
    this.setData({
      selectedCoupon: coupon,
      showCoupons: false
    })
    
    this.calculateOrderAmount()
  },

  /**
   * 取消优惠券
   */
  onCancelCoupon() {
    this.setData({ selectedCoupon: null })
    this.calculateOrderAmount()
  },

  /**
   * 确认购买
   */
  async onConfirmPurchase() {
    if (this.data.purchasing) return
    
    const { selectedPayment, order, course, selectedCoupon } = this.data
    
    // 检查余额支付
    if (selectedPayment === 'balance') {
      const balanceMethod = this.data.paymentMethods.find(m => m.id === 'balance')
      if (balanceMethod.balance < order.finalAmount) {
        wx.showToast({
          title: '余额不足',
          icon: 'none'
        })
        return
      }
    }
    
    try {
      this.setData({ purchasing: true })
      
      // 创建订单
      const orderData = {
        courseId: course.id,
        paymentMethod: selectedPayment,
        totalAmount: order.totalAmount,
        discountAmount: order.discountAmount,
        finalAmount: order.finalAmount,
        couponId: selectedCoupon?.id || null
      }
      
      Track.trackClick('course_purchase_confirm', 'purchase', orderData)
      
      const result = await this.createOrder(orderData)
      
      if (selectedPayment === 'wechat') {
        // 微信支付
        await this.processWechatPayment(result.orderId)
      } else {
        // 余额支付直接成功
        await this.processBalancePayment(result.orderId)
      }
      
    } catch (error) {
      Logger.error('Purchase failed', error)
      wx.showToast({
        title: error.message || '购买失败',
        icon: 'none'
      })
    } finally {
      this.setData({ purchasing: false })
    }
  },

  /**
   * 创建订单
   */
  async createOrder(orderData) {
    // 模拟API
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    return {
      orderId: `ORDER_${Date.now()}`,
      status: 'pending'
    }
  },

  /**
   * 微信支付处理
   */
  async processWechatPayment(orderId) {
    // 模拟调用支付接口
    const paymentData = await this.requestPayment(orderId)
    
    return new Promise((resolve, reject) => {
      wx.requestPayment({
        ...paymentData,
        success: (res) => {
          this.onPaymentSuccess(orderId)
          resolve(res)
        },
        fail: (err) => {
          Logger.error('Wechat payment failed', err)
          reject(new Error('支付失败'))
        }
      })
    })
  },

  /**
   * 请求支付参数
   */
  async requestPayment(orderId) {
    // 模拟API
    await new Promise(resolve => setTimeout(resolve, 500))
    
    return {
      timeStamp: String(Date.now()),
      nonceStr: 'random_string',
      package: 'prepay_id=wx_prepay_id',
      signType: 'RSA',
      paySign: 'payment_sign'
    }
  },

  /**
   * 余额支付处理
   */
  async processBalancePayment(orderId) {
    // 模拟API
    await new Promise(resolve => setTimeout(resolve, 800))
    
    this.onPaymentSuccess(orderId)
  },

  /**
   * 支付成功处理
   */
  onPaymentSuccess(orderId) {
    Track.trackClick('course_purchase_success', 'purchase', { orderId })
    
    wx.showToast({
      title: '购买成功',
      icon: 'success'
    })
    
    // 跳转到订单详情或课程详情
    setTimeout(() => {
      Router.redirectTo(`/packageOrder/pages/detail/index?id=${orderId}`)
    }, 1500)
  },

  /**
   * 查看课程详情
   */
  onViewCourse() {
    Router.navigateTo(`/packageTeacher/pages/courses/detail/index?id=${this.data.courseId}`)
  }
})
